package com.qingyun.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.qingyun.common.annotion.DataSource;
import com.qingyun.common.constant.DSEnum;
import com.qingyun.common.constant.tips.DistResult;
import com.qingyun.config.properties.GunsProperties;
import com.qingyun.core.util.FileUtil;
import com.qingyun.core.util.qr.WxQrCode;
import com.qingyun.modular.distributor.service.IDistributorLevelService;
import com.qingyun.modular.distributor.service.IDistributorService;
import com.qingyun.modular.distributor.vo.DistributorVo;
import com.qingyun.modular.model.Distributor;
import com.qingyun.modular.model.DistributorLevel;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 分销对外接口
 */

@Controller
@RequestMapping("/api/v1/")
public class DistributionController {

    @Autowired
    private IDistributorService distributorService;
    @Autowired
    private IDistributorLevelService distributorLevelService;
    @Resource
    private GunsProperties gunsProperties;

    private Logger logger =  LoggerFactory.getLogger(this.getClass());
    private String APIKEY="wxee9d2d30c0e8c2ed";//小程序id
    private String SECRETKEY="fe64c14adfea5772d4a784bc45c51197";//小程序密钥

    /**
     * 生成小程序二维码，打开自动成为他的分销商
     * @param userId
     */
    @GetMapping("/generateQr")
    @DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    @ResponseBody
    @ApiOperation(value = "查询会员信息")
    @ApiImplicitParam(name="userId",value="用户id",required = true,paramType = "query",dataType = "String")
    public void generateQr(String userId, HttpServletResponse response){
        logger.info("查询用户信息->开始查询会员信息:{}",userId);
        JSONObject data=new JSONObject();
        String accessToken = null;
        try{
            accessToken = WxQrCode.getAccessToken(APIKEY,SECRETKEY);
            logger.info("地址->:{}",gunsProperties.getFileUploadPath());
            byte [] qrCode = new WxQrCode().getminiqrQr(accessToken,gunsProperties.getFileUploadPath(),userId,response);
            response.getOutputStream().write(qrCode);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 扫码后将分佣人和当前用户绑定
     * @param userId
     */
    @GetMapping("/distribution")
    @DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    @ResponseBody
    @ApiOperation(value = "查询会员信息")
    @ApiImplicitParams({@ApiImplicitParam(name="userId",value="用户id",required = true,paramType = "query",dataType = "String"),@ApiImplicitParam(name="distributionUserId",value="用户id",required = true,paramType = "query",dataType = "String")})
    public DistResult distributionBinding(int userId,int distributionUserId){
        logger.info("绑定用户信息${}",userId);
        //查询当前用户是否存在分销商
        EntityWrapper<Distributor>  distributorEntityWrapper=new EntityWrapper<>();
        distributorEntityWrapper.eq("distributor_id",userId);
        Distributor existDistributor = distributorService.selectOne(distributorEntityWrapper);
        //没有分销商
        if(existDistributor==null){
            //创建分销对象
            Distributor newDistributor=new Distributor();
            //设置被分销用户ID
            newDistributor.setDistributorId(userId);
            //设置上级ID
            newDistributor.setSuperId(distributionUserId);
            //查询分销商的等级
            EntityWrapper<Distributor>  superDistributorEntityWrapper=new EntityWrapper<>();
            superDistributorEntityWrapper.eq("distributor_id",distributionUserId);
            Distributor superDistributor = distributorService.selectOne(superDistributorEntityWrapper);
            //如果上级分销商不存在，那说明是一级分销商
            if(superDistributor==null){
                newDistributor.setLevel(1);
            }else{
                //如果不是自动成为他的下一级
                int level = superDistributor.getLevel();
                if(level==3){
                    //最多只能有三级分销商
                    return DistResult.failure("分销商已达到最顶级");
                }
                newDistributor.setLevel(level+1);
            }
            distributorService.insert(newDistributor);
        }
        return DistResult.success();
    }

    /**
     * 设置分销等级比例
     * @param proportion
     */
    @GetMapping("/setDistributionLevel")
    @DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    @ResponseBody
    @ApiOperation(value = "设置分销等级比例")
    @ApiImplicitParam(name="proportion",value="比例",required = true,paramType = "query",dataType = "String")
    public DistResult setDistributionLevel(int id,Double proportion){
        logger.info("查询等级信息");
        DistributorLevel distributorLevel=distributorLevelService.selectById(id);
        distributorLevel.setProportion(proportion);
        distributorLevelService.updateById(distributorLevel);
        return DistResult.success();
    }


    /**
     * 查询分销用户
     * 根据用户ID查询所有层级的用户， 1级 2级 3级
     * @param userId
     */
    @GetMapping("/distribution/list")
    @DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    @ResponseBody
    @ApiOperation(value = "查询分销用户")
    @ApiImplicitParams({@ApiImplicitParam(name="userId",value="用户id",required = true,paramType = "query",dataType = "String"),@ApiImplicitParam(name="distributionUserId",value="用户id",required = true,paramType = "query",dataType = "String")})
    public DistResult getDistributorList(int userId){
        List<DistributorVo> distributorVos1=new ArrayList<>();
        List<DistributorVo> distributorLevel2=new ArrayList<>();
        List<DistributorVo> distributorLevel3=new ArrayList<>();
        EntityWrapper<Distributor> distributorEntityWrapper=new EntityWrapper<>();
        distributorEntityWrapper.eq("super_id",userId);
        List<Distributor> distributors = distributorService.selectList(distributorEntityWrapper);
        for (Distributor distributor:
                distributors) {
            DistributorVo distributorVo=new DistributorVo();
            distributorVo.setId(distributor.getId());
            distributorVo.setDistributorId(distributor.getDistributorId());
            distributorVo.setDistributorMobile(distributor.getDistributorMobile());
            distributorVo.setDistributorName(distributor.getDistributorName());
            distributorVo.setDistributorStatus(distributor.getDistributorStatus());
            distributorVo.setSuperId(distributor.getSuperId());
            distributorVo.setLevel(distributor.getLevel());
            distributorVo.setNickname(distributor.getNickname());
            distributorVos1.add(distributorVo);
            EntityWrapper<Distributor> distributorEntityWrapper2=new EntityWrapper<>();
            distributorEntityWrapper2.eq("super_id",distributor.getDistributorId());
            List<Distributor> distributors2 = distributorService.selectList(distributorEntityWrapper2);
            //distributorVo.setDistributorVos(distributorVos);
        }
        return DistResult.success(distributorVos1);
    }

}
